/**
 * 导出 ECharts 图表为图片
 * @param {EChartsType} chartInstance - ECharts 实例
 * @param {Object} options - 导出选项
 * @param {string} [options.type='png'] - 导出图片类型 ('png' | 'jpeg')
 * @param {string} [options.title='echarts图片'] - 导出文件名称
 * @param {number} [options.pixelRatio=2] - 导出图片分辨率比例
 * @param {string} [options.backgroundColor='#ffffff'] - 导出图片背景色
 * @returns {Promise<void>}
 */
export const exportChart = async (chartInstance, options = {}) => {
  if (!chartInstance) {
    throw new Error('Chart instance is required');
  }

  const {
    type = 'png',
    title = 'chart',
    pixelRatio = 2,
    backgroundColor = '#ffffff'
  } = options;

  try {
    // 获取图表的 base64 数据 URL
    const dataURL = chartInstance.getDataURL({
      type,
      pixelRatio,
      backgroundColor
    });

    // 创建一个临时链接元素
    const link = document.createElement('a');
    link.download = `${title}.${type}`;
    link.href = dataURL;
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (error) {
    console.error('Failed to export chart:', error);
    throw error;
  }
};

/**
 * 批量导出多个 ECharts 图表
 * @param {Array<{instance: EChartsType, title: string}>} charts - 图表实例和标题的数组
 * @param {Object} options - 导出选项
 * @returns {Promise<void>}
 */
export const exportMultipleCharts = async (charts, options = {}) => {
  if (!Array.isArray(charts) || charts.length === 0) {
    throw new Error('Charts array is required and cannot be empty');
  }

  for (const chart of charts) {
    if (!chart.instance || !chart.title) {
      throw new Error('Each chart must have an instance and title');
    }

    await exportChart(chart.instance, {
      ...options,
      title: chart.title
    });
  }
}; 